﻿using Rabbit.Common;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rabbit.Consumer.Dead
{
    internal class ReceiveDeadQue
    {
        /// <summary>
        /// 接收消息  消费死信队列
        /// </summary>
        public static void ReceiveDeadQueMsg()
        {
            //创建连接
            var conn = RabbitMQHelper.GetConnect();
            //创建信道
            var channel = conn.CreateModel();

            string deadExName = "DeadExchange";//死信交换机名称
            string deadQueName = "DeadQue";//死信队列名称
            string deadKey = "DeadKey";//死信路由名称

            //声明死信交换机
            channel.ExchangeDeclare(exchange: deadExName, type: "direct", durable: false, false, null);
            // 创建声明死信队列
            channel.QueueDeclare(deadQueName, durable: false, false, false, null);
            // 绑定死信队列
            channel.QueueBind(deadQueName, deadExName, deadKey, null);


            var consumer = new EventingBasicConsumer(channel);//消费者
            consumer.Received += (m, e) =>
            {
                //业务处理

                //二进制流转字符串 (Encoding.UTF8.GetString 方法是用于将UTF-8编码的字节数组转换为一个字符串的方法。)
                string msg = Encoding.UTF8.GetString(e.Body.ToArray());
                Console.WriteLine("已经消费了死信队列的消息:" + msg);



            };

            //慎用自动签收
            channel.BasicConsume(queue: "DeadQue", autoAck: true, consumer);//自动签收 (autoAck:true)

        }



    }
}
